﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;

namespace ProgNetComponentsDx.Controls.Design.TypeConverters
{
    public class GridColumnTypeConverter : TypeConverter
    {
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }
        public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            List<GridColumn> l = new List<GridColumn>();
            GridView gv = context.Instance.GetPropertyValue("GridView") as GridView;
            if (gv != null)
            {
                foreach (GridColumn c in gv.Columns)
                    l.AddIfNotExist(c);
            }
            return new StandardValuesCollection(l);
        }
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(GridColumn))
            {
                GridView gv = context.Instance.GetPropertyValue("GridView") as GridView;
                if (gv != null)
                {
                    foreach (GridColumn c in gv.Columns)
                        if (c.Name == value.AsString())
                            return c;
                }
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(GridColumn))
            {
                return true;
            }
            return base.CanConvertTo(context, destinationType);
        }
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            return base.CanConvertFrom(context, sourceType);
        }
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value != null && value is string)
            {
                GridView gv = context.Instance.GetPropertyValue("GridView") as GridView;
                if (gv != null)
                {
                    foreach (GridColumn c in gv.Columns)
                        if (c.Name == value.AsString())
                            return c;
                }
            }
            return value;
        }
    }
}
